<?php
namespace Kuoqi\Html;

class TableHtml{

    public $dataProvider;
    public $columns;
    public $classname;
    public $thHtml = '';
    public $tdHtml = '';
    public $pageStream = '';
    public $pageCfgs = array();

    public function __construct($opts){
        $this->dataProvider = isset($opts['dataProvider'])?$opts['dataProvider']:array();
        $this->columns = isset($opts['columns'])?$opts['columns']:array();
        $this->classname = isset($opts['classname'])?$opts['classname']:'';
        $this->pageStream = isset($opts['pageStream'])?$opts['pageStream']:'';
        $this->pageCfgs = isset($opts['pageCfgs'])?$opts['pageCfgs']:array();
    }

    public function pageConfig(){
        if($this->pageCfgs&&$this->pageStream){
            return sprintf('<tr><td colspan="99"><ul class="pager">%s</ul></td></tr>'
                ,$this->pageStream);
        }else{
            return '';
        }
    }

    public function flushToString(){
        $this->thHtml .='<tr>';
        foreach($this->columns as $col){
            $this->thHtml .= '<th>'.$col['attribute'].'</th>';
        }
        $this->thHtml .='</tr>';
        foreach($this->dataProvider as $item){
            $this->tdHtml .= '<tr>';
            foreach($this->columns as $col){
                $this->tdHtml .= sprintf('<td %s %s>%s</td>',
                    (isset($col['classname'])&&$col['classname'])?('class="'.$col['classname'].'"'):'',
                    isset($col['width'])?('width=\''.$col['width'].'\''):'',
                    $col['value']($item)
                );
            }
            $this->tdHtml .= '</tr>';
        }
        $table = sprintf('<table class="%s"><thead>%s</thead><tbody>%s%s</tbody></table>',
            $this->classname,
            $this->thHtml,
            $this->tdHtml,
            $this->pageConfig()
        );
        return $table;
    }

}